<template>
  <div class="list-wrap">
    <a-typography-title class="block-title" :heading="6">
      Rule Setup
    </a-typography-title>
    <a-select
      v-model="selectedIndustry"
      placeholder="Select Industry"
      @change="handleIndustryChange"
      style="width: 200px; margin-bottom: 20px"
    >
      <a-option
        v-for="industry in industries"
        :key="industry.id"
        :value="industry.id"
      >
        {{ industry.industry_name }}
      </a-option>
    </a-select>
    <a-button @click="toggleAllRules" style="margin-bottom: 20px">
      {{ isAllSelected ? 'Deselect All' : 'Select All' }}
    </a-button>

    <a-collapse :bordered="false">
      <a-collapse-item
        v-for="(rules, category) in rulesByCategory"
        :key="category"
        :header="category"
      >
        <template #extra> </template>

        <a-row class="list-row" :gutter="24">
          <a-col
            v-for="item1 in rules"
            :key="item1.id"
            :xs="12"
            :sm="12"
            :md="12"
            :lg="6"
            :xl="6"
            :xxl="6"
            class="list-col"
            style="min-height: 140px"
          >
            <CardWrap
              :loading="loading"
              :title="item1.name"
              :description="item1.comment"
              :comment="item1.regulation_content"
              :default-value="selectedRules.includes(item1.id)"
              :tag-text="$t('cardList.preset.tag')"
              @cardClick="handleCardClick(item1)"
              @switchClick="handleSwitchClick(item1)"
            >
            </CardWrap>
          </a-col>
        </a-row>
      </a-collapse-item>
    </a-collapse>

    <a-modal
      v-model:visible="isModalVisible"
      title="Rule Details"
      :width="800"
      :centered="true"
      :mask-closable="true"
      :closable="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="rule-details">
        <div><strong>Name:</strong> {{ selectedRule.name }}</div>
        <div><strong>regulation_content:</strong> {{ selectedRule.regulation_content }}</div>
        <div><strong>Comment:</strong> {{ selectedRule.comment }}</div>
        <div><strong>Category:</strong> {{ selectedRule.category }}</div>
        <div
          ><strong>Trigger Condition:</strong>
          {{ selectedRule.trigger_condition }}</div
        >
        <div
          ><strong>Required Columns:</strong>
          {{ selectedRule.required_columns }}</div
        >
        <div><strong>Parameters:</strong> {{ selectedRule.parameters }}</div>
        <div><strong>Priority:</strong> {{ selectedRule.priority }}</div>
        <div
          ><strong>Output Column:</strong> {{ selectedRule.output_column }}</div
        >
        <div>
          <strong>Logic:</strong>
          <a-textarea
            v-model="selectedRule.logic"
            :rows="10"
            :style="{ height: '200px' }"
          />
        </div>
        <div
          ><strong>Enabled:</strong>
          <a-switch v-model:value="selectedRule.enabled" disabled
        /></div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import axios from 'axios';
  import { ref, defineEmits, computed, onMounted, watch } from 'vue';
  import { queryRulesPresetListNew, RuleRecord } from '@/api/list';
  import useRequest from '@/hooks/request';
  import CardWrap from './card-wrap.vue';

  const emits = defineEmits(['update:selectedRules']);
  const selectedRules = ref<number[]>([]);
  const defaultValue: RuleRecord[] = new Array(6).fill({});
  const { loading, response: renderData } = useRequest<RuleRecord[]>(
    queryRulesPresetListNew,
    defaultValue
  );

  const isModalVisible = ref(false);
  const selectedRule = ref<RuleRecord>({
    id: 0,
    name: '',
    comment: '',
    description: '',
    category: '',
    trigger_condition: '',
    required_columns: [],
    parameters: '',
    priority: '',
    output_column: [],
    logic: '',
    enabled: false,
    regulation_content:''
  });
  const isAllSelected = computed(
    () => selectedRules.value.length === renderData.value.length
  );

  const selectedIndustry = ref<string | number>('all');
  const industries = ref([
    { id: 'all', industry_name: 'All Industries', rule_ids: '1,2,3' }, // Example industry with rule_ids
  ]);

  function toggleAllRules() {
    if (isAllSelected.value) {
      selectedRules.value = [];
    } else {
      selectedRules.value = renderData.value.map((rule) => rule.id);
    }
    emits('update:selectedRules', selectedRules.value);
    console.log('8.51');
    console.log(selectedRules);
  }

  watch(
    renderData,
    (newValue) => {
      if (newValue && newValue.length > 0) {
        toggleAllRules(); // 确保在数据加载后执行
      }
    },
    { immediate: true }
  );

  async function fetchIndustries() {
    try {
      const response = await axios.get('http://101.35.43.81:8111/api/industry');
      if (response.status === 200) {
        industries.value = [
          { id: 'all', industry_name: 'All Industries' },
          ...response.data.results,
        ];
        toggleAllRules();
      } else {
        console.error(`Failed to fetch industries: ${response.data.message}`);
      }
    } catch (error) {
      console.error('Error fetching industries:', error);
    }
  }

  onMounted(fetchIndustries);

  const filteredRules = computed(() => {
    let rules = [];

    if (selectedIndustry.value === 'all') {
      rules = renderData.value;
    } else {
      const selected = industries.value.find(
        (ind) => ind.id === selectedIndustry.value
      );
      if (selected && selected.rule_ids) {
        // Check if selected and rule_ids exist
        const ruleIds = selected.rule_ids.split(',').map(Number); // Correctly use rule_ids here
        rules = renderData.value.filter((rule) => ruleIds.includes(rule.id));
      }
    }

    // Sort rules by priority before returning
    return rules.sort((a, b) => a.priority - b.priority);
  });

  const rulesByCategory = computed(() => {
    const categories: Record<string, RuleRecord[]> = {};
    renderData.value.forEach((rule) => {
      const category = rule.category || 'Uncategorized';
      if (!categories[category]) {
        categories[category] = [];
      }
      categories[category].push(rule);
    });
    console.log(categories);
    return categories;
  });

  function handleIndustryChange(value) {
    selectedIndustry.value = value;
  }

  function handleCardClick(item: RuleRecord) {
    selectedRule.value = { ...item };
    isModalVisible.value = true;
  }

  function handleSwitchClick(item: RuleRecord) {
    const index = selectedRules.value.indexOf(item.id);
    if (index === -1) {
      selectedRules.value.push(item.id);
    } else {
      selectedRules.value.splice(index, 1);
    }
    emits('update:selectedRules', [...selectedRules.value]);
  }

  function sayHello() {
    console.log(rulesByCategory);
    console.log(renderData);
    console.log('test');
  }

  function handleOk() {
    isModalVisible.value = false;
  }

  function handleCancel() {
    isModalVisible.value = false;
  }
</script>

<style scoped lang="less">
  .list-wrap {
    padding: 20px;
  }

  .list-row {
    margin-top: 20px;
  }

  .list-col {
    cursor: pointer;
  }

  .rule-details {
    line-height: 1.5;
    max-height: 60vh;
    overflow-y: auto;
  }

  .rule-details div {
    margin-bottom: 8px;
  }
</style>
